import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { push, goBack } from "react-router-redux";
import { Form, Input, Button } from "antd";
import style from "./style.less";
import ErrTip from "../ErrTip";
import { GetMobileCode, userRegister } from "../../services/api/user";
import { errCode } from "../../helper/errCode";
const FormItem = Form.Item;

class RegisterCard extends PureComponent {
  state = {
    tipFont: "获取验证码",
    disableCode: true,
    index: 60,
    msgCode: true,
    timeStamp: ""
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) return;
      userRegister({
        ...values,
        country: "+86",
        username: values.mobile,
        return_type: "sync_json",
        register_type: "mobile_register",
        request_from: 1,
        appid: 1
      }).then(data => {
        const response = data.data && data.data.data;
        const flag = String(response.flag);
        if (flag !== "0") {
          console.log(flag, errCode[flag]);
          this.props.form.setFields({
            code: {
              value: values.code,
              errors: [new Error(errCode[flag])]
            }
          });
        } else {
          this.props.navigateTo("/resume");
        }
      });
    });
  };

  getCode = () => {
    this.props.form.validateFields(["mobile", "captcha"], (err, values) => {
      if (err) return;

      if (this.state.disableCode) {
        GetMobileCode({
          ...values,
          country: "+86",
          return_type: "json"
        }).then(data => {
          const response = data.data;
          const flag = String(response.flag);

          if (flag !== "0") {
            console.log(flag, errCode[flag]);
            if (flag === "5012") {
              this.props.form.setFields({
                mobile: {
                  value: values.mobile,
                  errors: [new Error(errCode[flag])]
                }
              });
            } else {
              this.changeImgCode();
              this.props.form.setFields({
                captcha: {
                  value: values.captcha,
                  errors: [new Error(errCode[flag])]
                }
              });
            }
          } else {
            this.timer = setInterval(() => {
              if (this.state.index <= 0) {
                return this.Clear();
              }

              this.setState({
                disableCode: false,
                index: this.state.index - 1,
                tipFont: `已发送(${this.state.index - 1}s)`
              });
            }, 999);
          }
        });
      }
    });
  };

  changeImgCode = () => {
    let date = new Date();
    let timeStamp = date.getTime();
    this.setState({ timeStamp });
  };

  Clear = () => {
    this.setState({
      disableCode: true,
      index: 60,
      tipFont: "获取验证码"
    });
    clearInterval(this.timer);
  };

  componentDidMount() {
    console.log(this.props);
  }

  render() {
    const { tipFont, disableCode, msgCode, timeStamp } = this.state;
    const { getFieldDecorator } = this.props.form;

    return (
      <div className={style.RegBox_pc}>
        <div className={style.greetRegister}>欢迎注册最佳东方</div>
        <Form onSubmit={this.handleSubmit} className={style.registerForm}>
          <FormItem>
            <div className={style.formItem}>
              {getFieldDecorator("mobile", {
                rules: [
                  {
                    pattern: /^1[3456789]\d{9}$/,
                    message: <ErrTip>请输入正确的手机号</ErrTip>
                  },
                  { required: true, message: <ErrTip>请输入常用手机号</ErrTip> }
                ],
                initialValue: ""
              })(
                <Input
                  addonBefore={""}
                  style={{ width: "100%" }}
                  placeholder="请输入常用手机号"
                  onFocus={this.clearErr}
                />
              )}
            </div>
          </FormItem>
          <FormItem>
            <div className={style.formItem}>
              {getFieldDecorator("captcha", {
                rules: [
                  { required: true, message: <ErrTip>请输入图形验证码</ErrTip> }
                ]
              })(
                <div className={style.codeWrap}>
                  <Input
                    className={`${style.formInput} ${style.code}`}
                    placeholder="请输入图形验证码"
                  />
                  <div className={style.imgCode} onClick={this.changeImgCode}>
                    <img src={`/u/captcha?t=${timeStamp}`} alt="" />
                  </div>
                </div>
              )}
            </div>
          </FormItem>
          <FormItem>
            <div className={style.formItem}>
              {getFieldDecorator("code", {
                rules: [
                  {
                    required: msgCode,
                    message: <ErrTip>请输入短信验证码</ErrTip>
                  }
                ]
              })(
                <div className={style.msgWrap}>
                  <Input
                    className={`${style.formInput} ${style.msg}`}
                    placeholder="请输入短信验证码"
                  />
                  <div
                    className={`${style.getMsg} ${
                      disableCode ? null : style.disabledCode
                    }`}
                    onClick={this.getCode}
                  >
                    {tipFont}
                  </div>
                </div>
              )}
            </div>
          </FormItem>
          <div>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              注 册
            </Button>
          </div>
          <div className={`${style.register} ${style.reg}`}>
            注册代表你已同意<a
              href="http://www.veryeast.cn/pcagree.html"
              rel="noopener noreferrer"
              target="_blank"
            >
              「最佳东方用户协议」
            </a>
          </div>
          <div className={style.goLogin}>
            <a onClick={() => this.props.navigateTo("/login")}>
              已有账号，直接登录
            </a>
          </div>
        </Form>
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {};
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    navigateTo: location => {
      dispatch(push(location));
    },
    goBack: () => {
      dispatch(goBack());
    }
  };
};

RegisterCard.propTypes = {
  login: PropTypes.object
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create()(RegisterCard));
